/**
 * API响应处理工具
 * 统一处理API响应，提供一致的错误处理和成功处理
 */

import { ElMessage } from 'element-plus';
import { logger } from './logger';

export interface IApiResponse<T = any> {
  code: number;
  msg: string;
  data: T;
}

export interface IApiError {
  message: string;
  code?: number;
  response?: any;
}

/**
 * API响应处理选项
 */
export interface IApiResponseOptions {
  /** 是否显示成功消息 */
  showSuccessMessage?: boolean;
  /** 是否显示错误消息 */
  showErrorMessage?: boolean;
  /** 成功消息文本 */
  successMessage?: string;
  /** 错误消息文本 */
  errorMessage?: string;
  /** 成功回调 */
  onSuccess?: (data: any) => void;
  /** 错误回调 */
  onError?: (error: IApiError) => void;
  /** 完成回调 */
  onFinally?: () => void;
}

/**
 * 处理API响应
 * @param response API响应数据
 * @param options 处理选项
 * @returns 处理后的数据或抛出错误
 */
export function handleApiResponse<T>(
  response: IApiResponse<T>,
  options: IApiResponseOptions = {}
): T {
  const {
    showSuccessMessage = false,
    showErrorMessage = true,
    successMessage,
    errorMessage,
    onSuccess,
    onError
  } = options;

  try {
    if (response.code === 0) {
      // 成功响应
      const data = response.data;
      
      if (showSuccessMessage) {
        const message = successMessage || response.msg || '操作成功';
        ElMessage.success(message);
      }
      
      onSuccess?.(data);
      return data;
    } else {
      // 业务错误
      const error: IApiError = {
        message: errorMessage || response.msg || '操作失败',
        code: response.code
      };
      
      if (showErrorMessage) {
        ElMessage.error(error.message);
      }
      
      onError?.(error);
      throw error;
    }
  } catch (err) {
    // 捕获其他错误
    const error: IApiError = {
      message: err instanceof Error ? err.message : '未知错误',
      code: -1
    };
    
    if (showErrorMessage) {
      ElMessage.error(error.message);
    }
    
    onError?.(error);
    throw error;
  }
}

/**
 * 处理API错误
 * @param error 错误对象
 * @param options 处理选项
 */
export function handleApiError(
  error: any,
  options: IApiResponseOptions = {}
): void {
  const {
    showErrorMessage = true,
    errorMessage,
    onError
  } = options;

  // 记录错误日志
  logger.error('API请求失败:', error);

  // 构建错误信息
  let message = errorMessage;
  if (!message) {
    if (error.response?.data?.msg) {
      message = error.response.data.msg;
    } else if (error.message) {
      message = error.message;
    } else {
      message = '请求失败，请重试';
    }
  }

  // 显示错误消息
  if (showErrorMessage && message) {
    ElMessage.error(message);
  }

  // 调用错误回调
  const apiError: IApiError = {
    message: message || '未知错误',
    code: error.response?.status,
    response: error.response
  };
  
  onError?.(apiError);
}

/**
 * 创建API请求包装器
 * @param apiCall API调用函数
 * @param options 响应处理选项
 * @returns 包装后的API调用函数
 */
export function createApiWrapper<T>(
  apiCall: () => Promise<IApiResponse<T>>,
  options: IApiResponseOptions = {}
) {
  return async (): Promise<T> => {
    try {
      const response = await apiCall();
      return handleApiResponse(response, options);
    } catch (error) {
      handleApiError(error, options);
      throw error;
    } finally {
      options.onFinally?.();
    }
  };
}

/**
 * 创建带参数的API请求包装器
 * @param apiCall API调用函数
 * @param options 响应处理选项
 * @returns 包装后的API调用函数
 */
export function createApiWrapperWithParams<T, P>(
  apiCall: (params: P) => Promise<IApiResponse<T>>,
  options: IApiResponseOptions = {}
) {
  return async (params: P): Promise<T> => {
    try {
      const response = await apiCall(params);
      return handleApiResponse(response, options);
    } catch (error) {
      handleApiError(error, options);
      throw error;
    } finally {
      options.onFinally?.();
    }
  };
}
